package softwaredepartment.zxit.com.pt_3280cinandroid.Utils;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by JohnsonChow on 16/4/22.
 */
public class DatabaseORMLiteHepler extends OrmLiteSqliteOpenHelper {
    private static final String Database_Name = "PT-3280C_N.db";
    private Map<String, Dao> daos = new HashMap<String, Dao>();

    /**
     * @param context 上下文.
     *                database_name 数据库名字.
     *                cursorFactory 可选的数据库游标工厂类，当查询(query)被提交时，该对象会被调用来实例化一个游标。默认为null.
     *                version 版本(默认为1).
     *                String database_name, SQLiteDatabase.CursorFactory cursorFactory,int version
     */
    DatabaseORMLiteHepler(Context context) {
        super(context, Database_Name, null, 1);

    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
//        try {
//            TableUtils.createTable(connectionSource, User.class);
//
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
//        try {
//            TableUtils.dropTable(connectionSource, User.class, true);
//
//            onCreate(sqLiteDatabase, connectionSource);
//        } catch (SQLException e) {
//            e.printStackTrace();
//        }
    }

    private static DatabaseORMLiteHepler instance;

    /**
     * 单例获取该DatabaseORMLiteHepler
     *
     * @param context
     * @return
     */
    public static synchronized DatabaseORMLiteHepler getDatabaseORMLiteHepler(Context context) {
        context = context.getApplicationContext();
        if (instance == null) {
            synchronized (DatabaseORMLiteHepler.class) {
                if (instance == null)
                    instance = new DatabaseORMLiteHepler(context);
            }
        }

        return instance;
    }

    public synchronized Dao getDao(Class clazz) throws SQLException {
        Dao dao = null;
        String className = clazz.getSimpleName();

        if (daos.containsKey(className)) {
            dao = daos.get(className);
        }
        if (dao == null) {
            dao = super.getDao(clazz);
            daos.put(className, dao);
        }
        return dao;
    }

    /**
     * 释放资源
     */
    @Override
    public void close() {
        super.close();

        for (String key : daos.keySet()) {
            Dao dao = daos.get(key);
            dao = null;
        }
    }

}

